<script>
import api from '@/api'
import box from '@/mixins/box'

export default {
  name: 'detail',
  mixins: [box],
  data() {
    return {
      id: 0,
      user: {
        // 用户昵称
        nickname: '',
        // 用户头像
        avatar: '',
      },
      // 房间信息
      house: {
        // 房间id
        id: 0,
        // 房间名称
        name: '',
        // 口令
        word_command: '',
        // 介绍
        content: '',
        // 奖品数量
        prize_num: 0,
        // 总价值
        prize_total_amount: 0,
        // 奖品列表
        prize_list: [],
        // 参与列表
        winner_list: [],
        // 中奖人数
        winner_num: 0,
        // 参与人数
        participation_num: 0,
        // 提前开奖人数
        begin_reward_num: 0,
        // 开奖时间
        begin_reward_at: 0,
        // 是否在房间内
        is_exist: 0,
        // 是否已结束
        is_finish: 0,
        // 进入房间次数
        // 1表示已读状态
        cishu: 0,
      },
      // 加载状态
      isLoading: true,
      // 当前选中的商品位置
      current: 0,
      // drawTime: 0,
      // 开奖时间
      time: {
        day: '999',
        hour: '999',
        minute: '999',
        second: '999',
      },
      // 定时器
      timer: 0,
      timer2: 1,
      left: 0,
      // 是否是已开奖的状态
      isDraw: false,
      // 加入房间输入的密码
      password: '',
      winnerPrize: {},
    }
  },
  onLoad(options) {
    this.id = options.id
  },
  onUnload() {
    clearInterval(this.timer)
    clearInterval(this.timer2)
  },
  onShow() {
    // 页面加载
    this.getHouseData(this.id)
  },
  onHide() {
    clearInterval(this.timer)
    clearInterval(this.timer2)
  },
  mounted() {
  },
  onReady() {
    // this.$refs.winnerDialog.show()
  },
  computed: {
    // 当前滚动位置选择的商品的价格信息
    currentPrice() {
      if (!this.house.prize_list.length) return '999'
      return this.house.prize_list[this.current].price
    },
    // 底部参与按钮的文本内容
    btnStr() {
      // 如果是已开奖的，或者房间状态为已结束状态的
      if (this.isDraw || this.house.is_finish === 2) {
        return '已开奖'
      } else if (this.house.is_exist === 1) {
        // 已参与
        return '已参加，等待开奖'
      }
      return '我要参与'
    },
    // 开奖时间
    drawTimeStr() {
      return this.isDraw ? '已开赏' : (`据开奖时间：${this.time.day}天${this.time.hour}时${this.time.minute}分${this.time.second}秒后`)
    },
    isWinner() {
      const uid = uni.getStorageSync('user_id')
      return this.house.winner_list.some(item => {
        if (item.is_winner && item.user_id === uid) {
          this.winnerPrize = item
          return true
        }
        return false
      })
    },
    isHomeOwner() {
      return uni.getStorageSync("user_id") === this.house.user_id
    }
  },
  methods: {
    // 监听滚动事件
    onScroll(e) {
      // 主打的就是能跑就行
      const scrollLeft = e.detail.scrollLeft
      const query = uni.createSelectorQuery().in(this)
      query.selectAll('.prize-item').boundingClientRect(data => {
        if (scrollLeft - this.left === 0) return
        const isRight = scrollLeft > this.left
        const position = isRight ? this.current + 1 : this.current - 1
        if (position === -1) return
        if (this.current === position) return

        // 判断是否在可视范围内 190为半个盒子的宽度
        if (data[position].left > 0 && data[position].left <= uni.upx2px(190)) {
          this.current = position
        }
        this.left = e.target.scrollLeft
      }).exec()
    },
    // 参与
    join() {
      if (this.btnStr !== '我要参与') {
        return
      }
      this.$refs.alertDialog.show()
    },
    onPrizeClick(e, index) {
      /*this.current = index
      this.left = uni.upx2px(280) * index*/
      /*this.prizeList.scrollLeft = this.left*/
      /*this.current = index
      this.left = uni.upx2px(280) * index*/
    },
    // 获取房间数据
    async getHouseData(id) {
      clearInterval(this.timer)
      clearInterval(this.timer2)
      await uni.showLoading()
      try {
        const result = await api.welfareHouses.detail(id)
        if (result.code === 200) {
          this.user.nickname = result.data.nickname
          this.user.avatar = result.data.avatar
          this.house = result.data
          // 获取完成数据之后就获取当前房间的开奖信息
          this.getDrawTime()
          return
        }
        throw new Error('获取数据失败')
      } catch (e) {
        await uni.showToast({ icon: 'none', title: e.message })
      } finally {
        uni.hideLoading()
      }
    },
    // 获取房间的参与人数，每10秒执行一次
    async getHouseNum() {
      const result = await api.welfareHouses.num(this.house.id)
      if (result.code === 200) {
        this.house.participation_num = result.data.num
      }
    },
    // 获取开奖时间
    getDrawTime() {
      // 已结束的不再进行判断
      if (this.house.is_finish === 2) {
        this.isDraw = true
        // 只有在进入第一次的时候才会进行显示中奖对话框
        // const uid =  uni.getStorageSync('uid')
        if (this.house.is_exist && this.house.cishu < 1) {
          this.$refs.winnerDialog.show()
        }
        return
      }
      if (this.isDraw) {
        return
      }
      // 判断是否是已开奖
      // 计算开奖时间
      const begin_reward_at = +new Date(this.house.begin_reward_at)
      // 标记是否是第一次判断已开奖，第一次无需再次刷新房间
      let isFirst = true
      const fn = () => {
        /*if (this.participationNum()) {
          // 人数够了
          this.isDraw = true
          clearInterval(this.timer)
          // 人数够了就直接开奖
          this.openPrize()
          return
        }*/
        const now = +new Date()
        // 判断是否已经到了开奖时间
        if (begin_reward_at - now > 0) {
          // 计算倒计时
          const time = (begin_reward_at - now) / 1000
          const day = Math.floor(time / 86400)
          const hour = this.fillTime(Math.floor(time / 3600 % 24))
          const minute = this.fillTime(Math.floor((time % 3600) / 60))
          const second = this.fillTime(Math.floor(time % 3600 % 60))
          this.time = {
            day,
            hour,
            minute,
            second,
          }
        } else {
          // console.log('已经到了开奖时间了')
          // 已经到了开奖时间了
          this.isDraw = true
          // 如果是第一次判断是否已已开奖，则无需再次刷新房间
          this.openPrize()
          /*if (this.isWinner) {
            this.isShowWinner = true
          }*/
          // this.$refs.winnerDialog.show()
          if (isFirst) {
          }
          clearInterval(this.timer)
        }
      }

      // 每10秒就获取当前房间的人数
      const fn2 = () => {
        if (this.isDraw) {
          clearInterval(this.timer2)
          return
        }
        this.getHouseNum()
      }

      // 倒计时实现
      this.timer = setInterval(() => {
        fn()
      }, 1000)

      this.timer2 = setInterval(() => {
        fn2()
      }, 10000)

      fn()
      // fn2()
      isFirst = false
    },
    // 当前房间参与人数是否已达到开奖人数
    participationNum() {
      return this.house.participation_num >= this.house.begin_reward_num
    },
    async openPrize() {
      // 开奖时，需对房间进行刷新
      // 重新加载数据
      // 开奖
      try {
        await api.welfareHouses.open(this.house.id)
        // 调用开奖接口，如果是200就表示开奖成功了
        // console.log(result)
      } catch (e) {
        console.log(e)
      } finally {
        await this.getHouseData(this.house.id)
      }
    },
    // 时间补零方法
    fillTime(n) {
      return n < 10 ? '0' + n : n
    },
    // 跳转获取参与人员的页面
    showJoinList() {
      if (!this.house.id) return
      this.header('/packageA/welfare/joinList?id=' + this.house.id, 1, false)
    },
    // 参与抽奖
    async joinPrize() {
      await uni.showLoading()
      try {
        const result = await api.welfareHouses.join({
          /* user_id: 13145,*/
          weal_room_id: this.house.id,
          room_password: this.password,
        })
        if (result.code !== 200) throw new Error(result.msg)
        await uni.showToast({ title: result.msg })
        setTimeout(() => {
          this.getHouseData(this.house.id)
        }, 500)
      } catch (e) {
        await uni.showToast({ icon: 'none', title: e.message, duration: 3000 })
      } finally {
        uni.hideLoading()
      }
    },
    copy() {
      uni.setClipboardData({
        data: this.house.word_command,
      })
    },
    async winnerDialogChange(show) {
      if (!show) {
        await api.welfareHouses.read(this.id)
      }
    },
    editHouse() {
      this.header('/packageA/welfare/create?id=' + this.house.id, 1, true)
    },
  },
}
</script>

<template>
  <view class="detail-layout">
    <!--   头部 -->
    <my-header background-color="transparent" fit-weixin title="福利屋">
      <template v-slot:menu>
        <text @click="$refs.popup.show" class="welfare-rule">规则</text>
      </template>
    </my-header>
    <!-- 主内容区域   -->
    <my-content class="welfare-detail-content">
      <scroll-view scroll-y="true" style="flex: 1; overflow-y: hidden;">
        <!--   房间基本信息     -->
        <view class="top item-bg">
          <!--    房主信息      -->
          <view class="user">
            <view class="border">
              <image mode="aspectFill" class="avatar" :src="user.avatar"></image>
            </view>
            <text class="nickname">{{ user.nickname }}</text>
            <view style="flex: 1;"></view>
            <!--     编辑房间       -->
            <!--            <image v-if="isHomeOwner" @click="editHouse" style="width: 40rpx;height: 40rpx;"
                   src="/static/images/user/edit-avatar.png"></image>-->
          </view>
          <view class="content">
            <view class="title">
              <view class="name">{{ house.name }}</view>
              <view class="word-command">活动口令: {{ house.word_command }}
                <image class="copy" src="https://www.dingxians.cn/upload/images/user/ic_copy.png" @click="copy"></image>
              </view>
            </view>
            <rich-text class="detail" :nodes="house.content"></rich-text>
          </view>
        </view>
        <!--   商品展示区域     -->
        <view class="prize item-bg">
          <view class="prize-header">
            <!--     开奖倒计时       -->
            <view class="drawTime">{{ drawTimeStr }}</view>
          </view>
          <scroll-view @scroll="onScroll" scroll-x="true" class="shang_box">
            <!--     商品列表       -->
            <view class="prize-list">
              <view class="prize-item"></view>
              <view class="prize-item" @click="onPrizeClick($event, index)" v-for="(item, index) in house.prize_list"
                :key="item.id" :class="[current === index ? 'active' : '']">
                <view class="prize-bg item-bg">
                  <image class="prize-img" mode="aspectFit" :src="item.image"></image>
                </view>
              </view>
              <view class="prize-item"></view>
            </view>
          </scroll-view>
          <!--    指示器      -->
          <!-- <view class="dot-list">
            <view class="dot-item" v-for="item in house.prize_num" :key="item"
                  :class="[current === item - 1 ? 'active' : '']"></view>
          </view> -->
          <view class="prizeValue">
            共
            <text class="prize-num">{{ house.prize_num }}</text>
            件,总价值
            <text class="prize-total-price">{{ house.prize_total_amount }}</text>
          </view>
          <!--          <view class="prize-price">
            <b>赏品价值：</b>
            <text class="prize-price-icon">￥</text>
            <text class="prize-price-amount" v-if="house.prize_list">{{ currentPrice }}</text>
          </view>-->
        </view>
        <!--   参与人员列表     -->
        <my-join-list :show-more="true" @showMore="showJoinList" :data="house.winner_list"
          :total="house.participation_num" :num="house.winner_num"></my-join-list>
      </scroll-view>
      <button class="btn-join btn-primary" :class="{ disable: btnStr !== '我要参与' }" @click="join">{{ btnStr }}</button>
    </my-content>

    <my-alert-dialog ref="popup" class="popup" :show-confirm="false" cancel-string="关闭">
      <view class="popup-content">
        <view>1.开箱福利屋为官方福利活动房间。在开放时间内，达到房间进场要求即可进入房间。</view>
        <view>2.用户创建福利屋需官方审核，审核通过即可开放。</view>
        <view>3.福利屋开奖时，房间无人参与，视为福利屋开奖失败福利屋会自动关闭，快邀请您的好友一起来参加福利吧</view>
        <view>4.福利屋开奖获得的赏品会直接下发至仓库，请注意查收。</view>
        <view>5.开奖的前一天截止报名</view>
      </view>
    </my-alert-dialog>

    <my-alert-dialog v-if="house.room_password" ref="alertDialog" :type="2" title="请输入房间密码" @confirm="joinPrize">
      <input type="number" class="pwd-edit" placeholder="请输入房间密码" v-model="password">
    </my-alert-dialog>
    <my-alert-dialog v-else ref="alertDialog" :type="2" title="提示" content="确定要参与嘛？" @confirm="joinPrize">
    </my-alert-dialog>

    <my-alert-dialog @change="winnerDialogChange" ref="winnerDialog" :type="2" title="提示" :show-confirm="false"
      cancel-string="关闭">
      <view class="winner-content">
        <template v-if="isWinner">
          <view class="winner-title">恭喜，你中奖了。</view>
          <image class="winner-prize-image" :src="winnerPrize.goods_image"></image>
          <view class="winner-prize-name">{{ winnerPrize.goods_name }}</view>
        </template>
        <template v-else>很遗憾，你没有中奖。</template>
      </view>
    </my-alert-dialog>
  </view>
</template>

<style scoped lang="scss">
.detail-layout {
  height: 100vh;
  background-image: url("https://www.dingxians.cn/upload/images/common/bg.png");
  background-size: 100% 100%;

  .welfare-detail-content {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  .welfare-rule {
    width: 56rpx;
    height: 56rpx;
  }

  .top {
    width: 702rpx;
    height: 312rpx;
    margin: 16rpx auto;
    padding: 30rpx 40rpx;
    box-sizing: border-box;


    .user {
      display: flex;
      align-items: center;
      width: 100%;
      /*padding: 40rpx 40rpx 0;*/
      color: white;

      .border {
        width: 100rpx;
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .avatar {
          width: 76rpx;
          height: 76rpx;
          border-radius: 50%;
        }
      }

      .nickname {
        margin-left: 18rpx;
        font-size: 32rpx;
        font-weight: bold;
      }

    }

    .content {
      margin-top: 25rpx;
      color: white;

      .title {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .name {
          font-weight: bold;
          font-size: 28rpx;
        }

        .word-command {
          font-size: 22rpx;
          color: #FFFDFD;

          .copy {
            width: 20rpx;
            height: 20rpx;
            margin-left: 6rpx;
          }
        }
      }

      .detail {
        margin-top: 15rpx;
        font-size: 24rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }

  .prize {
    margin: 0 auto;
    width: 710rpx;
    height: 560rpx;
    box-sizing: border-box;
    padding: 55rpx 32rpx 0;
    overflow: hidden;
    position: relative;

    .prize-header {
      display: flex;
      align-items: center;
      justify-content: center;

      .drawTime {
        font-size: 32rpx;
        font-weight: bold;
        color: #fff;
      }
    }

    .shang_box {
      height: 380rpx;

      .prize-list {
        display: flex;
        align-items: center;
        align-content: center;
        /*overflow-x: scroll;
      overflow-y: visible;*/
        margin: 40rpx auto 0;
        height: 310rpx;
        width: 630rpx;

        .prize-item {
          position: relative;
          flex-shrink: 0;
          width: 280rpx;
          height: 280rpx;

          &.active {
            z-index: 99;
            width: 70rpx;
            height: 280rpx;
          }

          /* 2, 5, 8, 11 */

          &.active .prize-bg {
            width: 310rpx;
            height: 310rpx;
            transform: translate(-120rpx, -16rpx);
            /*transform: translate(-16rpx -16rpx);*/
          }

          .prize-bg {
            width: 280rpx;
            height: 280rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .prize-img {
            height: 80%;
            width: 80%;
          }
        }
      }
    }


    .dot-list {
      display: flex;
      justify-content: center;

      .dot-item {
        margin-right: 8rpx;
        width: 8rpx;
        height: 8rpx;
        background-color: rgba(255, 255, 255, .5);

        &.active {
          background-color: white;
        }
      }
    }

    .prizeValue {
      color: white;
      font-size: 24rpx;
      display: flex;
      justify-content: center;
      margin-top: 30rpx;

      .prize-num,
      .prize-total-price {
        color: #45F5FF;
      }
    }

    .prize-price {
      position: absolute;
      bottom: 20rpx;
      left: 0;
      right: 0;
      margin: 0 auto;
      width: 400rpx;
      /*padding: 0 30rpx;*/
      height: 56rpx;
      line-height: 56rpx;
      text-align: center;
      background-image: url("https://www.dingxians.cn/upload/images/index/bg-price.png");
      background-size: 100% 100%;
      color: #D1D1D1;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .prize-price-icon {
        color: #DED000;
      }

      .prize-price-amount {
        color: #DED000;
        font-size: 40rpx;
      }
    }
  }

  .btn-join {
    width: 610rpx;
    height: 80rpx;
    font-size: 32rpx;
    margin: 20rpx auto;
    color: white;
    font-weight: bold;
    background-color: transparent;

    &.disable {
      filter: grayscale(1);
    }
  }

  .popup-content {
    padding: 30rpx;
  }

  /*
  .popup {
    z-index: 8888;

    .popup-content {
      width: 655rpx;
      height: 1100rpx;
      box-sizing: border-box;
      color: white;
      background-size: 100% 100%;
      background-image: url('https://www.dingxians.cn/upload/images/welfare/bg-dialog-rule.png');
      padding: 115rpx 40rpx 30rpx 40rpx;
    }

    .btn-close {
      width: 64rpx;
      height: 64rpx;
      position: absolute;
      right: 20rpx;
      top: 25rpx;
    }
  }
  */

  .pwd-edit {
    text-align: left;
    width: 680rpx;
    height: 100rpx;
    box-sizing: border-box;
    padding-left: 20rpx;
    line-height: 100rpx;
    color: white;
    border-radius: 16rpx;
    margin: 60rpx auto 40rpx;
    background: rgba(123, 125, 155, 0.35);
  }

  .winner-content {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    min-height: 200rpx;
    padding: 40rpx 0;

    .winner-title {
      font-size: 28rpx;
      margin-bottom: 20rpx;
    }

    .winner-prize-image {
      width: 200rpx;
      height: 200rpx;
    }

    .winner-prize-name {
      font-size: 28rpx;
      margin-top: 10rpx;
      text-align: center;
    }
  }
}
</style>